//
//  HXbluetoothLinkStyleCell.h
//  HongxuanBluetooth
//
//  Created by 广州弘轩科技发展有限公司 on 2023/8/4.
//

#import "BlueToothManager.h"


#define kPeripheralName @"622360099396"    // 设备名字
#define kServiceUUID @"FFF0"             // 服务的UUID
#define kCharacteristicUUID @"FFF6"      // 特征的UUID

#define WriteUUID1   @"FFE1"
#define NotifyUUID1  @"FFE1"

#define WriteUUID2   @"FFF1"
#define NotifyUUID2  @"FFF2"

//6E400002-B5A3-F393-E0A9-E50E24DCCA9E
#define WriteUUID3   @"6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define NotifyUUID3  @"6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

#define MOUserDefaults   [NSUserDefaults standardUserDefaults]

@interface BlueToothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (strong, nonatomic) NSMutableArray *deviceList;
@property (nonatomic, strong) CBPeripheral *selectedPeripheral;
@property (assign, nonatomic) BOOL oldLink;
@property (nonatomic, strong) NSMutableDictionary *dic;
@property (nonatomic, strong) NSString *linkedstr;
@property (nonatomic, assign) NSInteger jia;
@property (strong, nonatomic) NSMutableArray *connectPeripheralarray;
@property (strong, nonatomic) NSMutableArray *charcteristicarray;
@property (assign, nonatomic) BOOL isAutomaticLink;//自动链接
@property (strong, nonatomic)NSMutableArray *deviceListi ;

@end
@implementation BlueToothManager
@synthesize myDevices = _myDevices;
static BlueToothManager* instance;
+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
//        [instance initWith];
    });
    return instance;
}
+(id)allocWithZone:(struct _NSZone *)zone {
    return [BlueToothManager shareInstance];
}

-(id)copyWithZone:(struct _NSZone *)zone {
    return [BlueToothManager shareInstance];
}
- (NSMutableArray *)connectPeripheralarray{
    
    if(!_connectPeripheralarray){
        _connectPeripheralarray = [[NSMutableArray alloc] init];
        
    }
    return _connectPeripheralarray;
}
//deviceListi
- (NSMutableArray *)deviceListi{
    
    if(!_deviceListi){
        _deviceListi = [[NSMutableArray alloc] init];
        
    }
    return _deviceListi;
}

- (NSMutableArray *)charcteristicarray{
    
    if(!_charcteristicarray){
        _charcteristicarray = [[NSMutableArray alloc] init];
        
    }
    return _charcteristicarray;
}
-(void)StartScan{
    NSLog(@"蓝牙搜索");
    self.deviceList = [NSMutableArray array];
    self.jia = 0;
    if(!self.centralManager){
        self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        [self stopScan];
    }else{
//        [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"AF30"]] options:nil];
        [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"]] options:nil];
    }
//    [self.centralManager sta]
}
- (void)popupstop{
    [SVProgressHUD dismiss];
}
//- (void)startScan
//{
//    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
//    [self.centralManager scanForPeripheralsWithServices:self.dicoveredPeripherals options:options];
//}

-(void)stopScan{
//    [self.centralManager stopScan];
}
// 设备
//- (void)loadMyDevices {
//
//    NSArray *devices = [MOUserDefaults objectForKey:@"MyDevices"];
//
//    if (devices.count > 0) {
//        _myDevices = [NSMutableArray arrayWithArray:devices];
//    } else {
//        _myDevices = [NSMutableArray array];
//    }
//
//    NSLog(@"设备：%@", _myDevices);
//}

-(void)setMyDevices:(NSMutableArray *)myDevices{//存
    _myDevices = myDevices;
    NSData *data = [NSJSONSerialization dataWithJSONObject:myDevices options:NSJSONWritingPrettyPrinted error:nil];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"MyDevices"];
//    [MOUserDefaults setValue:myDevices forKey:@"MyDevices"];
//    [MOUserDefaults synchronize];
}

-(NSMutableArray *)myDevices{//取

    if (!_myDevices) {
        NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyDevices"];
        if (!data) {
            data = [NSData data];
        }
        _myDevices = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (!_myDevices) {
            _myDevices = [NSMutableArray array];
        }
        
//        NSArray *devices = [MOUserDefaults objectForKey:@"MyDevices"];
//
//        if (devices.count > 0) {
//            _myDevices = [NSMutableArray arrayWithArray:devices];
//        } else {
//            _myDevices = [NSMutableArray array];
//        }
    }
    return _myDevices;
}

//-(void)setOldUUID:(NSString *)oldUUID{
//    _oldUUID = oldUUID;
//    [[NSUserDefaults standardUserDefaults] setValue:oldUUID forKey:@"oldUUID"];
//}
//
//-(NSString *)oldUUID{
//    if (!_oldUUID) {
//        _oldUUID = [[NSUserDefaults standardUserDefaults] valueForKey:@"oldUUID"];
//    }
//    return _oldUUID;
//}



- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"蓝牙状态 :%@",central);
    // 蓝牙状态可用
    if (central.state == CBCentralManagerStatePoweredOn) {
        
        // 如果蓝牙支持后台模式，一定要指定服务，否则在后台断开连接不上，如果不支持，可设为nil, option里的CBCentralManagerScanOptionAllowDuplicatesKey默认为NO, 如果设置为YES,允许搜索到重名，会很耗电
//        [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil];
//        [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        
        
//        [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"AF30"]] options:nil];
        [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"]] options:nil];
        
        NSLog(@"蓝牙已开启 正在搜索蓝牙");
        self.bluetoothDiscoverable = YES;//已经打开
    }
    else {
        NSLog(@"蓝牙状态异常， 请检查后重试");
        self.bluetoothDiscoverable = NO;//蓝牙异常
        if(self.ConnectionFailureBlock){
            if(!kStringIsEmpty(self.uuid)){
                NSLog(@"数据为空");
                [[NSNotificationCenter defaultCenter]postNotificationName:@"bluetoothDisconnect" object:nil userInfo:@{@"uuid":self.uuid}];
            }
            
            self.ConnectionFailureBlock(self.uuid);
        }
        if(self.unitExceptionBlock ){
            self.unitExceptionBlock();
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
}


/**
 * 发现设备
 * @param peripheral 设备
 * @param advertisementData 广播内容
 * @param RSSI 信号强度
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    // 判断是否是你需要连接的设备
//    NSLog(@"%@",peripheral.name);
//    if ([peripheral.name isEqualToString:kPeripheralName]) {
//        peripheral.delegate = self;
//        self.selectedPeripheral = peripheral;
//        // 开始连接设备
//
//    }
    
//    if (!([peripheral.name hasPrefix:@"LS"] ||
//          [peripheral.name hasPrefix:@"ACD"] ||
//          [peripheral.name hasPrefix:@"62"] ||
//          [peripheral.name hasPrefix:@"CT"] ||
//          [peripheral.name hasPrefix:@"KT"]
//          )) {
//        return;
//    }
    
    
//    [self.centralManager connectPeripheral:peripheral options:nil];
    NSLog(@"发现的设备：%@ 广播信息：%@", peripheral.name,advertisementData);
#pragma mark - 新加参数 kCBAdvDataislink  1是链接
    NSMutableDictionary *advertisementData0 = [NSMutableDictionary dictionaryWithDictionary:advertisementData];
    [advertisementData0 setObject:@"" forKey:@"kCBAdvDataislink"];
    advertisementData = advertisementData0;
    
    NSLog(@"发现的设备：%@ 广播信息：%@", peripheral.name,advertisementData);
    NSLog(@"self.myDevices :%@",self.myDevices);
    BOOL isExist = NO;
//    for (NSDictionary *device in self.myDevices) {
//        NSString *uuidStr = device[@"uuid"];
//        if ([uuidStr isEqualToString:peripheral.identifier.UUIDString]) {
//            isExist = YES;
//            break;
//        }
//    }
    
    for (NSInteger i = self.myDevices.count; i > 0; i--) {
        NSDictionary *device = self.myDevices[i - 1];
        NSString *uuidStr = device[@"uuid"];
        if ([uuidStr isEqualToString:peripheral.identifier.UUIDString]) {
            isExist = YES;
            break;
        }
    }
    
    if (isExist && self.autoConnect == YES) { //自动连接
        
        self.isAutomaticLink = YES;
        
        [self stopScan];
//
//        [SVProgressHUD showWithStatus:NSLocalizedString(@"蓝牙连接中", nil) ];
        
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
        
        NSData *data = advertisementData[@"kCBAdvDataManufacturerData"];

        NSString *macString;

        if (data.length >= 8) {
            macString = [self getMacString:data];
            
        } else {
            macString = peripheral.identifier.UUIDString;
        }

        [self cancelperformSelector2];
//        之前延迟1.2秒 
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self connectWithPeripheral:peripheral advertisementData:advertisementData macString:macString];
            [self performSelector:@selector(connectingDeviceTimeOut:) withObject:nil afterDelay:6];
        });

//        return;
    }
    
    BOOL isAdded = NO;
    for (NSArray *pArr in self.deviceList) {
        CBPeripheral *p = pArr.firstObject;
        NSString *uuidStr1 = p.identifier.UUIDString;
        NSString *uuidStr2 = peripheral.identifier.UUIDString;
        if ([uuidStr1 isEqualToString:uuidStr2]) {
            isAdded = YES;
            break;
        }
    }
    
    if (!isAdded) {
        
        NSData *data = advertisementData[@"kCBAdvDataManufacturerData"];
        
        NSString *macString;
        
        if (data.length >= 8) {
            macString = [self getMacString:data];
        } else {
            macString = peripheral.identifier.UUIDString;
        }
       
        [self.deviceList addObject:@[peripheral,advertisementData,macString]];
//        [self setMyDevices:self.deviceList];
        
        if (self.refershDeviceList) {
            self.refershDeviceList(self.deviceList);
        }
    }
    NSLog(@"advertisementData:%@",advertisementData);
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:advertisementData];
    NSData *data = advertisementData[@"kCBAdvDataManufacturerData"];
    
    NSString *str = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
    [dic setObject:str forKey:@"kCBAdvDataManufacturerData"];
    [dic setObject:@"" forKey:@"kCBAdvDataTimestamp"];
    [dic setObject:@"" forKey:@"kCBAdvDataEquipmenttime"];//添加新的。设备发送的时间
    [dic setObject:@"" forKey:@"kCBAdvDataislink"];//新添加是否链接 1链接 0为链接
    NSArray *arr = dic[@"kCBAdvDataServiceUUIDs"];
    if(arr == nil){
        NSLog(@"arr 空了 kCBAdvDataServiceUUIDs没有 导致崩溃:%@",arr);
        arr = dic[@"kCBAdvDataHashedServiceUUIDs"];
    }
    [dic setObject:[arr componentsJoinedByString:@","] forKey:@"kCBAdvDataServiceUUIDs"];
    [self.dic setObject:dic forKey:peripheral.identifier.UUIDString];
    
    NSLog(@"RSSI:%@",RSSI);
}

//读取到信号回调
-(void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error
{
    

//    NSLog(@"读取到信号：%ld",(long)[RSSI integerValue]);
    
    if(self.RSSIBlock){
        self.RSSIBlock([RSSI integerValue]);
    }

    
}
//- (void)scanForPeripheralsWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs options:(nullable NSDictionary<NSString *, id> *)options;

/**
 * 已经连接上设备
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    // 停止扫描
//    [self.centralManager stopScan];
    self.connectionState = YES;
    // 发现服务
    [self.selectedPeripheral discoverServices:nil];
    peripheral.delegate = self;
    [peripheral discoverServices:nil];
    NSLog(@"对应设备： %@",peripheral.identifier.UUIDString);
    NSLog(@"链接成功对应的蓝牙信息：%@",peripheral);
    [SVProgressHUD dismiss];
    
    [self cancelperformSelector];
    self.uuid = peripheral.identifier.UUIDString;
    if (self.connectPeripheral == peripheral) {

        
//        NSDictionary *advertisementData = self.dic[peripheral.identifier.UUIDString];
//        if(!advertisementData){
//            advertisementData = [NSDictionary dictionary];
//        }
        NSString *name ;
        if ( peripheral.name == nil) {
            NSLog(@"peripheral.name:%@",peripheral.name);
            name = @"";
        }else{
            name = [NSString stringWithFormat:@"%@",peripheral.name];
        }
        if(self.oldLink == NO){
            NSDictionary *dic = @{@"name": name,@"uuid":peripheral.identifier.UUIDString,@"advertisementData" : self.dic[peripheral.identifier.UUIDString]};
            if(![self.myDevices  containsObject:dic]){
                [self.myDevices addObject:dic];
                [self setMyDevices:self.myDevices];
            }
        }else{
            self.oldLink = YES;
        }
/*     //原先的成功返回
        if(self.successfulConnectionBlock){
            self.successfulConnectionBlock(@[peripheral].mutableCopy);
        }
        */
//        新加的返回
        NSDictionary *dic = @{@"name": peripheral.name,@"uuid":peripheral.identifier.UUIDString,@"advertisementData" : self.dic[peripheral.identifier.UUIDString]};
        self.deviceListi = @[peripheral,dic];
//        if(self.successfulConnectionBlock){
//            self.successfulConnectionBlock(deviceListi);
//        }
        //新加的
        [self.connectPeripheralarray addObject:peripheral];
    }
    
    // 4.1.3 读取RSSI的值
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(readRSSIInfo) userInfo:nil repeats:YES];
}

// 读RSSI值
- (void)readRSSIInfo
{
    [self.connectPeripheral readRSSI];
    
}
/**
 * 已经发现服务
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    
    NSLog(@"已经发现服务peripheral :%@",peripheral);
//    for (CBService *service in peripheral.services) {
//        if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
//            // 根据你要的那个服务去发现特性
//            [self.selectedPeripheral discoverCharacteristics:nil forService:service];
//        }
//
//        // 这里我是根据 180A 用来获取Mac地址，没什么实际作用，可删掉
//        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"180A"]]) {
//            [self.selectedPeripheral discoverCharacteristics:nil forService:service];
//        }
//    }
    
    if (error) {
        return;
    }
    
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}


/**
 * 已经发现特性
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if(self.bluetoothConnectionReturnBlock){
        self.bluetoothConnectionReturnBlock();//蓝牙连接中返回
    }
    if (self.isPopupStop) {
        self.isPopupStop = NO;
    }else{
        [SVProgressHUD showSuccessWithStatus:@"successfu lconnection"];
    }
//    [SVProgressHUD showSuccessWithStatus:@"successfu lconnection"];
    NSLog(@"peripheralone 2:%@",peripheral);
    
    NSLog(@"service : %@  service.characteristics :%@ service.characteristics[0]:%@",service ,service.characteristics,service.characteristics[0]);
//    
//    [self.charcteristicarray addObject:service.characteristics[0]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
//
//    for (CBCharacteristic *characteristic in service.characteristics) {
//        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A23"]]) {
//            // 这里是读取Mac地址， 可不要， 数据固定， 用readValueForCharacteristic， 不用setNotifyValue:setNotifyValue
//            [self.selectedPeripheral readValueForCharacteristic:characteristic];
//        }
//
//
//        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
//            // 订阅特性，当数据频繁改变时，一般用它， 不用readValueForCharacteristic
//            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
//
//            // 获取电池电量
//            unsigned char send[4] = {0x5d, 0x08, 0x01, 0x3b};
//            NSData *sendData = [NSData dataWithBytes:send length:4];
//
//            // 这里的type类型有两种 CBCharacteristicWriteWithResponse CBCharacteristicWriteWithoutResponse，它的属性枚举可以组合
//            [self.selectedPeripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
//
//            /*
//             characteristic 属性
//             typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
//             CBCharacteristicPropertyBroadcast                                                = 0x01,
//             CBCharacteristicPropertyRead                                                    = 0x02,
//             CBCharacteristicPropertyWriteWithoutResponse                                    = 0x04,
//             CBCharacteristicPropertyWrite                                                    = 0x08,
//             CBCharacteristicPropertyNotify                                                    = 0x10,
//             CBCharacteristicPropertyIndicate                                                = 0x20,
//             CBCharacteristicPropertyAuthenticatedSignedWrites                                = 0x40,
//             CBCharacteristicPropertyExtendedProperties                                        = 0x80,
//             CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)        = 0x100,
//             CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)    = 0x200
//             };
//             */
//
//            NSLog(@"%@",characteristic);
//            // 打印结果为 <CBCharacteristic: 0x1702a2a00, UUID = FFF6, properties = 0x16, value = (null), notifying = NO>
//
//            //  我的结果 为 0x16  (0x08 & 0x16)结果不成立， （0x04 & 0x16）结果成立，那写入类型就是 CBCharacteristicPropertyWriteWithoutResponse
//        }
//    }
    
    if (error) {
        return;
    }
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        
        if (self.connectPeripheral == peripheral) {
            
            if ([characteristic.UUID.UUIDString isEqualToString:NotifyUUID3] ||
                [characteristic.UUID.UUIDString isEqualToString:NotifyUUID3]) {
                //接收通知
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
//            先备份
          
            if ([characteristic.UUID.UUIDString isEqualToString:WriteUUID3] ||
                [characteristic.UUID.UUIDString isEqualToString:WriteUUID3]) {
                //写的Charcteristic
                self.writeCharcteristic = characteristic;
//                NSString *dataStr = @"AA0406123456";
//                NSData *data = [NSData dataWithBytes:CFBridgingRetain(dataStr) length:11];
//                NSString *crc = [data getCrc16Modbus];
//            //    NSLog(@"crc = %@",crc);
//                crc = @"1F";
//                NSString *str = [NSString stringWithFormat:@"%@%@55",dataStr,crc ];
//                str = @"AA04061234561434554355";
//                [self writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"didConnectPeripheral" object:@"1"];
//                self.isConnect = YES;
                
                
                
//                if(self.characteristicBlock){
//                    self.characteristicBlock(characteristic);
//                }
                
                if(self.successfulConnectionBlock){
                    NSLog(@"self.deviceListi 1 :%@",self.deviceListi);
                    
                    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.deviceListi[1]];
                    NSMutableDictionary *mudic = [NSMutableDictionary dictionaryWithDictionary:dict[@"advertisementData"]];
//                    [mudic setObject:characteristic forKey:@"kCBAdvDatacharacteristic"];
//                    [mudic setObject:self.deviceListi[0] forKey:@"kCBAdvDataconnectPeripheral"];

                    NSDictionary *nutadict = @{@"uuid":self.deviceListi[1][@"uuid"],@"advertisementData":mudic,@"name":self.deviceListi[1][@"name"]};
                    
                    
                    
                    self.deviceListi = @[self.deviceListi[0],nutadict];
                    
                    NSLog(@"self.deviceListi 2 :%@",self.deviceListi);
                    
                    self.successfulConnectionBlock(self.deviceListi);
                }
                NSLog(@"✅已连接1! 开始读生产信息");
                NSLog(@"self.writeCharcteristic :%@",self.writeCharcteristic);
                
                [self.charcteristicarray addObject:characteristic];
                
                
//                // 读生产信息
//                [[BlueToothManager shareInstance] readDeviceInfo];
                
//                NSMutableArray *dataarray = [[NSMutableArray alloc] init];
//                [dataarray addObject:peripheral];
//                [dataarray addObject:characteristic];
//                //新加的
//                [self.connectPeripheralarray addObjectsFromArray:dataarray];
                 
            }
            

//            if([self.linkedstr isEqualToString:@"one"]){
//                if ([characteristic.UUID.UUIDString isEqualToString:WriteUUID3] ||
//                    [characteristic.UUID.UUIDString isEqualToString:WriteUUID3]) {
//                    //写的Charcteristic
//                    self.towCharcteristic = characteristic;
//    //                NSString *dataStr = @"AA0406123456";
//    //                NSData *data = [NSData dataWithBytes:CFBridgingRetain(dataStr) length:11];
//    //                NSString *crc = [data getCrc16Modbus];
//    //            //    NSLog(@"crc = %@",crc);
//    //                crc = @"1F";
//    //                NSString *str = [NSString stringWithFormat:@"%@%@55",dataStr,crc ];
//    //                str = @"AA04061234561434554355";
//    //                [self writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
//    //                [[NSNotificationCenter defaultCenter] postNotificationName:@"didConnectPeripheral" object:@"1"];
//    //                self.isConnect = YES;
//                    NSLog(@"✅已连接1! 开始读生产信息");
//                    NSLog(@"self.writeCharcteristic :%@",self.towCharcteristic);
//                    self.linkedstr = @"tow";
//                    /*
//                    // 读生产信息
//                    [[BlueToothManager shareInstance] readDeviceInfo];
//                     */
//                }
//            }else{
//                if ([characteristic.UUID.UUIDString isEqualToString:WriteUUID3] ||
//                    [characteristic.UUID.UUIDString isEqualToString:WriteUUID3]) {
//                    //写的Charcteristic
//                    self.writeCharcteristic = characteristic;
//    //                NSString *dataStr = @"AA0406123456";
//    //                NSData *data = [NSData dataWithBytes:CFBridgingRetain(dataStr) length:11];
//    //                NSString *crc = [data getCrc16Modbus];
//    //            //    NSLog(@"crc = %@",crc);
//    //                crc = @"1F";
//    //                NSString *str = [NSString stringWithFormat:@"%@%@55",dataStr,crc ];
//    //                str = @"AA04061234561434554355";
//    //                [self writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
//    //                [[NSNotificationCenter defaultCenter] postNotificationName:@"didConnectPeripheral" object:@"1"];
//    //                self.isConnect = YES;
//                    NSLog(@"✅已连接1! 开始读生产信息");
//                    NSLog(@"self.writeCharcteristic :%@",self.writeCharcteristic);
//                    self.linkedstr = @"one";
//                    /*
//                    // 读生产信息
//                    [[BlueToothManager shareInstance] readDeviceInfo];
//                     */
//                }
//            }
        }
    }
    
    
}


/**
 * 数据更新的回调
 */
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    // 这里收到的数据都是16进制，有两种转换，一种就直接转字符串，另一种是转byte数组，看用哪种方便
    
    // 直接转字符串
    NSString *orStr = characteristic.value.description;
    NSString *str = [orStr substringWithRange:NSMakeRange(1, orStr.length - 2)];
    NSString *dataStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"dataStr = %@",dataStr);
    NSLog(@"orStr = %@",orStr);
    NSLog(@"orStr = %@",orStr);
    
    
    
    
//    0x7b22636f756e74223a36357d
    // 转Byte数组
    Byte *byte = (Byte *)characteristic.value.bytes;
    NSLog(@"byte :%s",byte);
    
    if(self.dataBlock){
        self.dataBlock(characteristic.value);
    }
    if(self.datastrBlock){
        self.datastrBlock(dataStr);
    }
    if(self.datalasttimeBlock){
        self.datalasttimeBlock(dataStr);
    }
    
    
    
    
    
    //_______________________________________________________________________________________________________________
    
    // 解析你的协议，附几个解协议或许能用到的函数
    
    //  unsigned long value = strtoul([subStr UTF8String], 0, 16); 把16进制的字符串，按十进制整数输出
    // [self binaryDataWithStr:str]; 十六进制的字符串转换成2进制的字符串,自己写的函数，用于复杂协议的戒子
    // [self byteWithInteger:num], 十进制转字节，用于发送命令；
}


/**
 * 设备连接断开
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    // 让它自动重连
//    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil];
    
    
    self.connectPeripheral = nil;
    self.adData = nil;
    self.connectionState = NO;
    self.theMac = @"";
    self.uuid = @"";
    self.uuid = [NSString stringWithFormat:@"%@",peripheral.identifier];
//    [BlueToothManager shareInstance].theMac
    NSLog(@"设备断开的信息 central：%@ peripheral:%@  connectPeripheral:%@  peripheral.identifier:%@",central,peripheral,self.connectPeripheral ,peripheral.identifier);
    NSLog(@"设备连接断开");
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"BlueToothManagerData" objiect:nil userInfo:@{@"userInfo":;peripheral.identifier}];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DisconnectBluetoothdevice" object:nil userInfo:nil];
    
//    [SVProgressHUD showSuccessWithStatus:@"device disconnected"];
    if(self.bluetoothConnectionReturnBlock){
        self.bluetoothConnectionReturnBlock();//蓝牙连接中返回
    }
    if (self.isPopupStop) {
        self.isPopupStop = NO;
    }else{
//        [SVProgressHUD showWithStatus:NSLocalizedString(@"bluetooth connection", nil) ];
        [SVProgressHUD showErrorWithStatus:@"device disconnected"];
        if(self.isAutomaticLink){
            NSLog(@"自动链接成功返回1");
            self.isAutomaticLink = NO;
            if(self.automaticLinkBlock){
                self.automaticLinkBlock();
            }
        }
    }
//    [SVProgressHUD showErrorWithStatus:@"device disconnected"];
    if(self.ConnectionFailureBlock){
        if(!kStringIsEmpty(self.uuid)){
            NSLog(@"数据为空");
            [[NSNotificationCenter defaultCenter]postNotificationName:@"bluetoothDisconnect" object:nil userInfo:@{@"uuid":self.uuid}];
        }
     
        self.ConnectionFailureBlock(self.uuid);
        
    }
}


/**
 * 写入成功的回调， 如果类型是CBCharacteristicWriteWithoutResponse，不会走这个方法；
 */
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    [self.selectedPeripheral readValueForCharacteristic:characteristic];
}

//#program mark  -获取Mac地址
- (NSString *)getMacString:(NSData *)data {
    
    NSString *value = @"";
    
    NSMutableString *macString = [[NSMutableString alloc]init];
    
    for (int i = 0; i < data.length; i++) {
        int a = 0;
        [data getBytes:&a range:NSMakeRange(i, 1)];
        value = [value stringByAppendingString:[NSString stringWithFormat:@"%.2x",a]];
    }
    
    NSLog(@"测试: %@",value);

    [macString appendString:[[value substringWithRange:NSMakeRange(4,2)] uppercaseString]];
    [macString appendString:@":"];

    [macString appendString:[[value substringWithRange:NSMakeRange(6,2)] uppercaseString]];
    [macString appendString:@":"];

    [macString appendString:[[value substringWithRange:NSMakeRange(8,2)] uppercaseString]];
    [macString appendString:@":"];

    [macString appendString:[[value substringWithRange:NSMakeRange(10,2)] uppercaseString]];
    [macString appendString:@":"];

    [macString appendString:[[value substringWithRange:NSMakeRange(12,2)] uppercaseString]];
    [macString appendString:@":"];
    
    [macString appendString:[[value substringWithRange:NSMakeRange(14,2)] uppercaseString]];
    
    return macString;
}

- (void)cancelperformSelector2{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchDeviceTimeOut:) object:nil];
}

- (void)cancelperformSelector {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectingDeviceTimeOut:) object:nil];
}
- (void)searchDeviceTimeOut:(id)info {
    if(self.bluetoothConnectionReturnBlock){
        self.bluetoothConnectionReturnBlock();//蓝牙连接中返回
    }
    if (self.isPopupStop) {
        self.isPopupStop = NO;
    }else{
        if(self.isAutomaticLink){
            self.isAutomaticLink = NO;
        }
        [SVProgressHUD showErrorWithStatus:@"reconnecting the device timed out, please try again!"];
    }
    
//    [SVProgressHUD showErrorWithStatus:@"reconnecting the device timed out, please try again!"];
   
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat Width = screenWidth - 80.0;

//    AgainConnectD *agc = [AgainConnectD createViewFromNib];
//    agc.frame = CGRectMake(agc.frame.origin.x, agc.frame.origin.y, Width, 150);
//    [agc showInWindowWithBackgoundTapDismissEnable:YES];
//    agc.againFindBlock = ^(void){
//        self.gotoTabBar = 1;
//        if(self.findBlock){
//            self.findBlock();
//        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoTiaozhuan" object:nil];
//    };
//
//    agc.againConnectBlock = ^(void){
//        [self reConnectLastDevice];
//    };
//    [SVProgressHUD dismiss];
}
//连接超时调用的方法
- (void)connectingDeviceTimeOut:(id)info {
    if(self.bluetoothConnectionReturnBlock){
        self.bluetoothConnectionReturnBlock();//蓝牙连接中返回
    }
    if (self.isPopupStop) {
        self.isPopupStop = NO;
    }else{

        [SVProgressHUD showErrorWithStatus:@"reconnecting the device timed out, please try again!"];
    }
//    [SVProgressHUD showErrorWithStatus:@"reconnecting the device timed out, please try again!"];
    if(self.requestTimeoutBlock){
        self.requestTimeoutBlock(self.deviceList);//请求超时返回
    }
    NSLog(@"重新连接设备超时, 请重试!");
//    [SVProgressHUD dismiss];
//    NSLog(@"连接超时");
//    self.isConnect = false;
}

#pragma mark - connect
- (void)connectWithPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData macString:(NSString *)macString {
    if(self.bluetoothConnectionReturnBlock){
        self.bluetoothConnectionReturnBlock();//蓝牙连接中返回
    }
    if (self.isPopupStop) {
        self.isPopupStop = NO;
    }else{
        
        [SVProgressHUD showWithStatus:NSLocalizedString(@"bluetooth connection", nil) ];
    }
    if(self.isAutomaticLink){
        NSLog(@"自动链接成功返回2");
        self.isAutomaticLink = NO;
        if(self.automaticLinkBlock){
            self.automaticLinkBlock();
        }
    }
    
//    [SVProgressHUD showWithStatus:NSLocalizedString(@"bluetooth connection", nil) ];
    self.connectPeripheral = peripheral;
    self.adData = advertisementData;
    NSLog(@"self.adData :%@",self.adData);
    self.theMac = macString;
    [self.centralManager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
    [self performSelector:@selector(connectingDeviceTimeOut:) withObject:nil afterDelay:6];
    
    
}
-(void)reconnection:(NSString *)UUID{
    self.theMac = UUID;
    self.uuid = UUID;
//    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"AF30"]] options:nil];
//    6E400001-B5A3-F393-E0A9-E50E24DCCA9E
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"]] options:nil];
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:UUID]] options:nil];
    NSUUID *macID= [[NSUUID alloc] initWithUUIDString:UUID];
    NSArray *arr = [self.centralManager retrievePeripheralsWithIdentifiers:@[macID]];
    if(arr.count>0) {
        [SVProgressHUD showWithStatus:NSLocalizedString(@"bluetooth connection", nil) ];
        self.oldLink = YES;
        self.connectPeripheral = arr[0];
        self.connectPeripheral.delegate = self;
        [self.centralManager connectPeripheral:self.connectPeripheral options:nil];
        [self performSelector:@selector(connectingDeviceTimeOut:) withObject:nil afterDelay:6];
    }
}
/*
//1 读生产信息
//蓝牙连接后，需要向仪器读一次生产信息，确保仪器是正常的。如果回复08码，需提示“仪器连接异常”
- (void)readDeviceInfo {
    
    // 超时处理
//    [self performSelector:@selector(readDeviceInfoDelay) withObject:nil afterDelay:6];
    
//    // 方法1
//    NSArray *dataArray = @[@"0xab", @"0x47", @"0x00", @"0x00", @"0x00", @"0x00", @"0x14", @"0x00", @"0x33", @"0xc4"];
//    [[BlueToothManager shared] writeDataArr:dataArray];
    
    SInt16 i = 0xAA;
    SInt16 i1 = 0x04;
    SInt16 i2 = 0x06;
    SInt16 i3 = arc4random() % 255;
    SInt16 i4 = arc4random() % 255;
    SInt16 i5 = arc4random() % 255;
    SInt16 i6 = arc4random() % 255;
    SInt16 i7 = arc4random() % 255;
    SInt16 i8 = arc4random() % 255;

    int toal = i3+i4+i5+i6+i7+i8;
    int s = [NSString BaseSystem16ToBaseSystem10:[NSString stringWithFormat:@"%d",i1]].intValue + [NSString BaseSystem16ToBaseSystem10:[NSString stringWithFormat:@"%d",i2]].intValue;
    toal += s;
    NSString *str = [NSString BaseSystem10ToBaseSystem16:[NSString stringWithFormat:@"%d",toal]];
    
    if(str.length > 2){
    
        if(str.length >= 2){
            NSString *c = [str substringWithRange:NSMakeRange(str.length - 2,2)];//
            c = [NSString BaseSystem16ToBaseSystem10:c];
            toal = c.intValue;
        }
    }
    SInt16 i9 = toal;
    SInt16 i10 = 0x55;
    Byte send[] = {i, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10};
    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
    [[BlueToothManager shareInstance] writeData:sendData];
    
    NSLog(@"%@",self.connectPeripheral.identifier.UUIDString);

}
*/
- (void)writeData:(NSData *)data {
    self.jia ++;
//    NSLog(@"connectPeripheralarray :%@",self.connectPeripheralarray);
//    self.towPeripheral = self.connectPeripheralarray[0];
//    NSLog(@"towPeripheral :%@",self.towPeripheral);
//    NSLog(@"towPeripheral.name :%@",self.towPeripheral.name);
    
    
#pragma mark - 测试
    if (data && self.writeCharcteristic && self.connectPeripheral) {

        NSLog(@"\n***********************发送数据：%@",data);
        NSLog(@"connectPeripheralarray :%@",self.connectPeripheralarray);
        NSLog(@"self.charcteristicarray :%@",self.charcteristicarray);
        
        
        
        [self.connectPeripheral writeValue:data forCharacteristic:self.writeCharcteristic type:CBCharacteristicWriteWithoutResponse];
        
        
        if(self.connectPeripheralarray.count != self.charcteristicarray.count){
            NSLog(@"有特性没返回全，先不发送获取蓝牙数据");
//            return;
        }
        
//        // bluetoothddataArray 是需要处理的目标数组
//
//        // array2 是去掉相同元素后的数组
//        NSMutableArray *array2 = [NSMutableArray array];
//
//        for (NSString *str in self.connectPeripheralarray) {//遍历数组1
//            if (![array2 containsObject:str]) {//判断数组2中有没有该元素,如果没有就添加到数组2中,该步骤就是去掉数组中的重复元素
//                [array2 addObject:str];
//                NSLog(@"去重的数据 1%@",array2);
//                self.connectPeripheralarray = [NSMutableArray arrayWithArray:array2];
//            }
//        }
//
//        // bluetoothddataArray 是需要处理的目标数组
//
//        // array2 是去掉相同元素后的数组
//        NSMutableArray *array3 = [NSMutableArray array];
//
//        for (NSString *str in self.charcteristicarray) {//遍历数组1
//            if (![array3 containsObject:str]) {//判断数组2中有没有该元素,如果没有就添加到数组2中,该步骤就是去掉数组中的重复元素
//                [array3 addObject:str];
//                NSLog(@"去重的数据 2%@",array3);
//                self.charcteristicarray = [NSMutableArray arrayWithArray:array3];
//            }
//        }
//
//
//        if(self.connectPeripheralarray.count != self.charcteristicarray.count){
//            NSLog(@"有特性没返回全，先不发送获取蓝牙数据");
//            return;
//        }
////        先备份
////        [self.connectPeripheral writeValue:data forCharacteristic:self.writeCharcteristic type:CBCharacteristicWriteWithoutResponse];
//
//        for (int i = 0; i <self.connectPeripheralarray.count; i ++) {
//
//            self.towPeripheral = self.connectPeripheralarray[i];
//            self.charcteristic = self.charcteristicarray[i];
//
//            NSLog(@"发送需要的数据 %@: %@ :%@",data,self.charcteristic, self.towPeripheral);
//            NSLog(@"self.towPeripheral.identifier %@",self.towPeripheral.identifier);
//            [self.towPeripheral writeValue:data forCharacteristic:self.charcteristic type:CBCharacteristicWriteWithoutResponse];
//
//
//        }
    }

    
#pragma mark - 正式
////    最终的
//    if (data && self.writeCharcteristic && self.connectPeripheral) {
//
//        NSLog(@"\n***********************发送数据：%@",data);
//        NSLog(@"writeCharcteristic :%@",self.connectPeripheral.name);
//
//        for (int i = 0; i <self.connectPeripheralarray.count; i ++) {
//
//            self.towPeripheral = self.connectPeripheralarray[i];
//
//            [self.towPeripheral writeValue:data forCharacteristic:self.writeCharcteristic type:CBCharacteristicWriteWithoutResponse];
//        }
//    }
//
    
    
}


- (void)writeDatatow:(NSData *)data uuid:(NSString *)uuid{
    self.jia ++;
//    NSLog(@"connectPeripheralarray :%@",self.connectPeripheralarray);
//    self.towPeripheral = self.connectPeripheralarray[0];
//    NSLog(@"towPeripheral :%@",self.towPeripheral);
//    NSLog(@"towPeripheral.name :%@",self.towPeripheral.name);
    
    
#pragma mark - 测试
    if (data && self.writeCharcteristic && self.connectPeripheral) {

        NSLog(@"\n***********************发送数据：%@",data);
        NSLog(@"connectPeripheralarray :%@",self.connectPeripheralarray);
        NSLog(@"self.charcteristicarray :%@",self.charcteristicarray);
        
        
        
//        [self.connectPeripheral writeValue:data forCharacteristic:self.writeCharcteristic type:CBCharacteristicWriteWithoutResponse];
        
        
        if(self.connectPeripheralarray.count != self.charcteristicarray.count){
            NSLog(@"有特性没返回全，先不发送获取蓝牙数据");
//            return;
        }
        
        // bluetoothddataArray 是需要处理的目标数组

//        // array2 是去掉相同元素后的数组
//        NSMutableArray *array2 = [NSMutableArray array];
//
//        for (NSString *str in self.connectPeripheralarray) {//遍历数组1
//            if (![array2 containsObject:str]) {//判断数组2中有没有该元素,如果没有就添加到数组2中,该步骤就是去掉数组中的重复元素
//                [array2 addObject:str];
//                NSLog(@"去重的数据 1%@",array2);
//                self.connectPeripheralarray = [NSMutableArray arrayWithArray:array2];
//            }
//        }
//
//        // bluetoothddataArray 是需要处理的目标数组
//
//        // array2 是去掉相同元素后的数组
//        NSMutableArray *array3 = [NSMutableArray array];
//
//        for (NSString *str in self.charcteristicarray) {//遍历数组1
//            if (![array3 containsObject:str]) {//判断数组2中有没有该元素,如果没有就添加到数组2中,该步骤就是去掉数组中的重复元素
//                [array3 addObject:str];
//                NSLog(@"去重的数据 2%@",array3);
//                self.charcteristicarray = [NSMutableArray arrayWithArray:array3];
//            }
//        }


        if(self.connectPeripheralarray.count != self.charcteristicarray.count){
            NSLog(@"有特性没返回全，先不发送获取蓝牙数据");
            return;
        }
//        先备份
//        [self.connectPeripheral writeValue:data forCharacteristic:self.writeCharcteristic type:CBCharacteristicWriteWithoutResponse];

        for (int i = 0; i <self.connectPeripheralarray.count; i ++) {
            
            self.towPeripheral = self.connectPeripheralarray[i];
            self.charcteristic = self.charcteristicarray[i];

            NSLog(@"发送需要的数据 %@: %@ :%@",data,self.charcteristic, self.towPeripheral);
            NSLog(@"self.towPeripheral.identifier %@",self.towPeripheral.identifier);
            NSLog(@"uuid :%@",uuid);
            NSString *strid = [NSString stringWithFormat:@"%@",self.towPeripheral.identifier];
            if([uuid isEqualToString:strid]){
                NSLog(@"一样的ID");
                [self.towPeripheral writeValue:data forCharacteristic:self.charcteristic type:CBCharacteristicWriteWithoutResponse];
            }
//            [self.towPeripheral writeValue:data forCharacteristic:self.charcteristic type:CBCharacteristicWriteWithoutResponse];


        }
    }

    
#pragma mark - 正式
////    最终的
//    if (data && self.writeCharcteristic && self.connectPeripheral) {
//
//        NSLog(@"\n***********************发送数据：%@",data);
//        NSLog(@"writeCharcteristic :%@",self.connectPeripheral.name);
//
//        for (int i = 0; i <self.connectPeripheralarray.count; i ++) {
//
//            self.towPeripheral = self.connectPeripheralarray[i];
//
//            [self.towPeripheral writeValue:data forCharacteristic:self.writeCharcteristic type:CBCharacteristicWriteWithoutResponse];
//        }
//    }
//
    
    
}

-(NSMutableDictionary *)dic{
    if(!_dic){
        _dic = [NSMutableDictionary dictionary];
    }
    return _dic;
}
//断开链接
-(void)disconnect{
    
//    self.connectPeripheral = nil;
    self.adData = nil;
    self.connectionState = NO;
    self.theMac = @"";
    self.uuid = @"";
    NSLog(@"self.connectPeripheral:%@",self.connectPeripheral);
    if (!self.connectPeripheral) {
        
        return;
    }
    [self.centralManager cancelPeripheralConnection:self.connectPeripheral];
}



@end
